<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
    <title>订单详情 - 商户端</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="${pageContext.request.contextPath}/logo/favicon.ico">
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .sidebar {
            min-height: calc(100vh - 56px);
        }
        .table-success {
            background-color: #d1e7dd;
        }
    </style>
</head>
<body>
    <jsp:include page="../common/header.jsp"/>
    
    <div class="container-fluid">
        <div class="row">
            <jsp:include page="../common/sidebar.jsp"/>
            
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="pt-3">
                    <h1 class="h2 mb-4">订单详情</h1>
                    
                    <c:if test="${order != null}">
                        <!-- 订单信息 -->
                        <div class="card mb-3">
                            <div class="card-header bg-success text-white">
                                <h5 class="mb-0">订单信息</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <div class="col-md-6">
                                        <p><strong>订单编号：</strong>${order.orderNo}</p>
                                        <p><strong>下单时间：</strong><fmt:formatDate value="${order.createTime}" pattern="yyyy-MM-dd HH:mm:ss"/></p>
                                        <p><strong>订单状态：</strong>
                                            <c:choose>
                                                <c:when test="${order.status == 0}"><span class="badge bg-warning">待付款</span></c:when>
                                                <c:when test="${order.status == 1}"><span class="badge bg-info">待发货</span></c:when>
                                                <c:when test="${order.status == 2}"><span class="badge bg-primary">待收货</span></c:when>
                                                <c:when test="${order.status == 3}"><span class="badge bg-success">已完成</span></c:when>
                                                <c:when test="${order.status == 4}"><span class="badge bg-danger">已取消</span></c:when>
                                                <c:when test="${order.status == 5}"><span class="badge bg-secondary">售后中</span></c:when>
                                            </c:choose>
                                        </p>
                                        <c:if test="${order.paymentMethod != null}">
                                            <p><strong>支付方式：</strong>${order.paymentMethod}</p>
                                        </c:if>
                                        <c:if test="${order.paymentTime != null}">
                                            <p><strong>支付时间：</strong><fmt:formatDate value="${order.paymentTime}" pattern="yyyy-MM-dd HH:mm:ss"/></p>
                                        </c:if>
                                    </div>
                                    <div class="col-md-6">
                                        <p><strong>收货人：</strong>${order.receiverName}</p>
                                        <p><strong>联系电话：</strong>${order.receiverPhone}</p>
                                        <p><strong>收货地址：</strong>${order.deliveryAddress}</p>
                                        <c:if test="${order.logisticsCompany != null}">
                                            <p><strong>物流公司：</strong>${order.logisticsCompany}</p>
                                            <p><strong>物流单号：</strong>${order.logisticsNo}</p>
                                        </c:if>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 商品明细 -->
                        <div class="card mb-3">
                            <div class="card-header bg-success text-white">
                                <h5 class="mb-0">商品明细</h5>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead class="table-success">
                                            <tr>
                                                <th>商品名称</th>
                                                <th>单价</th>
                                                <th>数量</th>
                                                <th>小计</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <c:forEach var="item" items="${order.orderItems}">
                                                <tr>
                                                    <td>${item.productName}</td>
                                                    <td>¥<fmt:formatNumber value="${item.price}" pattern="#,##0.00"/></td>
                                                    <td>${item.quantity}</td>
                                                    <td>¥<fmt:formatNumber value="${item.subtotal}" pattern="#,##0.00"/></td>
                                                </tr>
                                            </c:forEach>
                                        </tbody>
                                        <tfoot>
                                            <tr>
                                                <td colspan="3" class="text-end"><strong>订单总额：</strong></td>
                                                <td><strong class="text-danger">¥<fmt:formatNumber value="${order.totalAmount}" pattern="#,##0.00"/></strong></td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>
                            </div>
                        </div>
                        
                        <div class="text-center">
                            <c:if test="${order.status == 1}">
                                <button type="button" class="btn btn-success" 
                                        onclick="openShipModal(${order.orderId}, '${order.orderNo}')">发货</button>
                            </c:if>
                            <a href="${pageContext.request.contextPath}/merchant/order" class="btn btn-secondary">返回订单列表</a>
                        </div>
                    </c:if>
                    
                    <c:if test="${order == null}">
                        <div class="alert alert-danger">订单不存在或无权查看</div>
                        <a href="${pageContext.request.contextPath}/merchant/order" class="btn btn-secondary">返回订单列表</a>
                    </c:if>
                </div>
            </main>
        </div>
    </div>
    
    <!-- 发货模态框 -->
    <div class="modal fade" id="shipModal" tabindex="-1" aria-labelledby="shipModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-success text-white">
                    <h5 class="modal-title" id="shipModalLabel">订单发货</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="shipForm">
                        <input type="hidden" id="shipOrderId" name="orderId">
                        <div class="mb-3">
                            <label class="form-label">订单编号</label>
                            <input type="text" class="form-control" id="shipOrderNo" readonly>
                        </div>
                        <div class="mb-3">
                            <label for="logisticsCompany" class="form-label">物流公司 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="logisticsCompany" name="logisticsCompany" required>
                            <div class="invalid-feedback">请输入物流公司</div>
                        </div>
                        <div class="mb-3">
                            <label for="logisticsNo" class="form-label">物流单号 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="logisticsNo" name="logisticsNo" required>
                            <div class="invalid-feedback">请输入物流单号</div>
                        </div>
                        <div class="alert alert-danger d-none" id="shipError"></div>
                        <div class="alert alert-success d-none" id="shipSuccess"></div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-success" id="submitShipBtn" onclick="submitShip()">确认发货</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="${pageContext.request.contextPath}/js/bootstrap.bundle.min.js"></script>
    <script>
        let shipModal = null;
        
        // 初始化模态框
        document.addEventListener('DOMContentLoaded', function() {
            shipModal = new bootstrap.Modal(document.getElementById('shipModal'));
        });
        
        // 打开发货模态框
        function openShipModal(orderId, orderNo) {
            document.getElementById('shipOrderId').value = orderId;
            document.getElementById('shipOrderNo').value = orderNo;
            document.getElementById('logisticsCompany').value = '';
            document.getElementById('logisticsNo').value = '';
            document.getElementById('shipError').classList.add('d-none');
            document.getElementById('shipSuccess').classList.add('d-none');
            document.getElementById('logisticsCompany').classList.remove('is-invalid');
            document.getElementById('logisticsNo').classList.remove('is-invalid');
            shipModal.show();
        }
        
        // 提交发货
        function submitShip() {
            const orderId = document.getElementById('shipOrderId').value;
            const logisticsCompany = document.getElementById('logisticsCompany').value.trim();
            const logisticsNo = document.getElementById('logisticsNo').value.trim();
            
            // 清除之前的错误状态
            document.getElementById('logisticsCompany').classList.remove('is-invalid');
            document.getElementById('logisticsNo').classList.remove('is-invalid');
            
            const errors = [];
            
            if (!logisticsCompany) {
                errors.push('物流公司');
                document.getElementById('logisticsCompany').classList.add('is-invalid');
            }
            
            if (!logisticsNo) {
                errors.push('物流单号');
                document.getElementById('logisticsNo').classList.add('is-invalid');
            }
            
            if (errors.length > 0) {
                showShipError('请检查以下字段：' + errors.join('、'));
                return;
            }
            
            const submitBtn = document.getElementById('submitShipBtn');
            submitBtn.disabled = true;
            submitBtn.textContent = '发货中...';
            
            document.getElementById('shipError').classList.add('d-none');
            document.getElementById('shipSuccess').classList.add('d-none');
            
            const params = new URLSearchParams();
            params.append('orderId', orderId);
            params.append('logisticsCompany', logisticsCompany);
            params.append('logisticsNo', logisticsNo);
            
            fetch('${pageContext.request.contextPath}/merchant/order/ship', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                },
                body: params.toString()
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showShipSuccess(data.message);
                    setTimeout(function() {
                        shipModal.hide();
                        location.reload();
                    }, 1500);
                } else {
                    showShipError(data.message || '发货失败');
                    submitBtn.disabled = false;
                    submitBtn.textContent = '确认发货';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showShipError('发货失败，请重试');
                submitBtn.disabled = false;
                submitBtn.textContent = '确认发货';
            });
        }
        
        function showShipError(message) {
            const errorDiv = document.getElementById('shipError');
            errorDiv.textContent = message;
            errorDiv.classList.remove('d-none');
        }
        
        function showShipSuccess(message) {
            const successDiv = document.getElementById('shipSuccess');
            successDiv.textContent = message;
            successDiv.classList.remove('d-none');
        }
    </script>
</body>
</html>

